/* 
    主页面
*/

import { CloseOutlined, PlusOutlined } from '@ant-design/icons'
import { Breadcrumb, Button, Card, Layout } from 'antd'
import React, { useEffect, useState } from 'react'
import { Route, Routes, useNavigate } from 'react-router-dom'

import { ApiClient } from '../shared/request'
import CardDetail from './CardDetail'


const { Header, Content } = Layout


const AppLayout = () => {
    const [cards, setCards] = useState([])

    useEffect(() => {
        ApiClient.cards().then((resp) => {
            console.log(resp)
            setCards(resp)
        })
    }, [])

    const addCard = () => {
        const newCard = { title: '标题', content: '正文' }
        ApiClient.create(newCard).then((resp) => {
            console.log("创建", resp)
            setCards([...cards, resp])
        })
    }

    const removeCard = (id) => {
        ApiClient.delete({}, id).then((resp) => {
            setCards(cards.filter(card => card.id !== id))
        })
    }

    let option = {
        cards: cards,
        addCard: addCard,
        removeCard: removeCard
    }

    return (
        <Layout className="layout" style={{ minHeight: '100vh' }}>
            <Header>
                <div className='logo'></div>
            </Header>

            <Content style={{ padding: '0 50px' }}>
                {BreadcrumbList()}

                <div className="site-layout-content">
                    {CardList(option)}
                </div>
            </Content>
        </Layout>
    )
}


const CardList = (option) => {
    const navigate = useNavigate()
    return (
        <Routes>
            <Route path="/" element={
                <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-4">
                    {option.cards.map((card) => (
                        <Card
                            key={card.id}
                            title={card.title ? card.title : `标题`}
                            extra={<CloseOutlined onClick={() => option.removeCard(card.id)} />} // 删除点击
                            bordered={false}
                            onDoubleClick={() => navigate(`/home/card/${card.id}`)} // 双击子页面
                        >
                            {card.content}
                        </Card>
                    ))}
                    <Button type="primary"
                        shape="circle" icon={<PlusOutlined />}
                        size={'large'}
                        className="fixed bottom-5 right-5"
                        onClick={option.addCard}
                    />
                </div>
            } />
            <Route path="/card/:id" element={<CardDetail />} />
        </Routes>
    )
}

const BreadcrumbList = () => {
    return <Breadcrumb separator=">" items={[
        {
            title: 'Home',
            href: '/home',
        },
    ]} />
}

export default AppLayout
